// 用户管理控制器
const { User, MembershipLevel } = require('../models');
const { hashPassword, paginate, generatePagination } = require('../utils/tools');

// 显示用户列表
exports.showUsers = async (req, res) => {
  try {
    const { page = 1, pageSize = 10, search = '' } = req.query;
    
    // 构建查询条件
    const query = {};
    if (search) {
      query[Op.or] = [
        { username: { [Op.like]: `%${search}%` } },
        { email: { [Op.like]: `%${search}%` } }
      ];
    }
    
    // 获取分页数据
    const paginatedQuery = paginate(query, { page, pageSize });
    const { count, rows } = await User.findAndCountAll({
      where: paginatedQuery,
      include: ['membershipLevel'],
      order: [['createdAt', 'DESC']]
    });
    
    // 生成分页信息
    const pagination = generatePagination(count, page, pageSize);
    
    // 获取所有会员等级
    const membershipLevels = await MembershipLevel.findAll();
    
    res.render('users/index', {
      title: '用户管理',
      users: rows,
      pagination,
      search,
      membershipLevels
    });
  } catch (error) {
    console.error('获取用户列表错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 显示添加用户页面
exports.showAddUser = async (req, res) => {
  try {
    const membershipLevels = await MembershipLevel.findAll();
    res.render('users/add', {
      title: '添加用户',
      membershipLevels
    });
  } catch (error) {
    console.error('获取会员等级错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 添加用户
exports.addUser = async (req, res) => {
  const { username, email, password, membershipLevelId, isMember, isAdmin } = req.body;
  
  try {
    // 检查邮箱是否已存在
    const existingUser = await User.findOne({ where: { email } });
    if (existingUser) {
      req.flash('error', '邮箱已被使用');
      return res.redirect('/admin/users/add');
    }
    
    // 创建用户
    await User.create({
      username,
      email,
      password: await hashPassword(password),
      membershipLevelId,
      isMember: isMember === 'on',
      isAdmin: isAdmin === 'on'
    });
    
    req.flash('success', '用户添加成功');
    res.redirect('/admin/users');
  } catch (error) {
    console.error('添加用户错误:', error);
    req.flash('error', '添加用户失败');
    res.redirect('/admin/users/add');
  }
};

// 显示编辑用户页面
exports.showEditUser = async (req, res) => {
  try {
    const user = await User.findByPk(req.params.id, {
      include: ['membershipLevel']
    });
    
    if (!user) {
      req.flash('error', '用户不存在');
      return res.redirect('/admin/users');
    }
    
    const membershipLevels = await MembershipLevel.findAll();
    
    res.render('users/edit', {
      title: '编辑用户',
      user,
      membershipLevels
    });
  } catch (error) {
    console.error('获取用户信息错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 更新用户
exports.updateUser = async (req, res) => {
  const { username, membershipLevelId, isMember, isAdmin } = req.body;
  
  try {
    const user = await User.findByPk(req.params.id);
    
    if (!user) {
      req.flash('error', '用户不存在');
      return res.redirect('/admin/users');
    }
    
    // 更新用户信息
    await user.update({
      username,
      membershipLevelId,
      isMember: isMember === 'on',
      isAdmin: isAdmin === 'on'
    });
    
    req.flash('success', '用户更新成功');
    res.redirect('/admin/users');
  } catch (error) {
    console.error('更新用户错误:', error);
    req.flash('error', '更新用户失败');
    res.redirect(`/admin/users/edit/${req.params.id}`);
  }
};

// 删除用户
exports.deleteUser = async (req, res) => {
  try {
    const user = await User.findByPk(req.params.id);
    
    if (!user) {
      req.flash('error', '用户不存在');
      return res.redirect('/admin/users');
    }
    
    // 防止删除最后一个管理员
    const adminCount = await User.count({ where: { isAdmin: true } });
    if (user.isAdmin && adminCount <= 1) {
      req.flash('error', '不能删除唯一的管理员账户');
      return res.redirect('/admin/users');
    }
    
    await user.destroy();
    
    req.flash('success', '用户删除成功');
    res.redirect('/admin/users');
  } catch (error) {
    console.error('删除用户错误:', error);
    req.flash('error', '删除用户失败');
    res.redirect('/admin/users');
  }
};